package pe.sonrisas.tools.mysql;


import java.awt.Image;
import java.io.*;
import java.sql.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import pe.sonrisas.tools.dao.PersonaDAO;

/**
 *
 * @author DIEGOALV
 */
public class FotoPacienteDAOMysql {

    Conexion_BD co = new Conexion_BD();
    private Image data;
    CallableStatement cs;

    public void guardarFoto(String id, String ruta) {

        try {
            //Connection connection = DriverManager.getConnection("jdbc:odbc:Sonrisas");
            //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            co.Conectar();
            cs = co.getCn().prepareCall("{CALL usp_registrar_fotopaciente (?,?)}");

            // PreparedStatement ps = connection.prepareStatement("insert into FOTO_PACIENTE (codpaciente, foto) values (? , ?)");
            
                FileInputStream fis = null;
                try {
                    co.getCn().setAutoCommit(false);
                    cs.setString(1, id);
                    File file = new File(ruta);
                    fis = new FileInputStream(file);

                    cs.setBlob(2, fis, (int) file.length());
                    //      cs.setBinaryStream(2, fis, (int) file.length());

                    cs.setBlob(2, fis, (int)file.length());
                    //cs.setBinaryStream(2, fis, (int) file.length());

                    cs.executeUpdate();
                    co.getCn().commit();
                    System.out.println("Ingreso foto");
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException es) {
                    co.getCn().rollback();
                    cs.close();
                } finally {
                    try {
                        co.getCn().setAutoCommit(true);
                        fis.close();
                        co.Desconectar();
                    } catch (Exception ex) {
                        Logger.getLogger(PersonaDAO.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException se) {
            System.out.println("ERROR: " + se.getMessage());
        }
    }

    public boolean modificarFoto(String id, String ruta) {
        boolean modifico = false;
        try {


            co.Conectar();
            cs = co.getCn().prepareCall("{CALL usp_modificar_fotopaciente (?,?)}");
          //  Connection connection = co.getCn();
          //  PreparedStatement ps = connection.prepareStatement("update FOTO_PACIENTE set foto = ? where idpaciente = ?");
         
            {
                FileInputStream fis = null;
                try {
                    cs.setString(1, id);
                    co.getCn().setAutoCommit(false);
                    File file = new File(ruta);
                    fis = new FileInputStream(file);
                    cs.setBinaryStream(2, fis, (int) file.length());
                    cs.executeUpdate();
                    co.getCn().commit();
                    modifico = true;
                    System.out.println("entrooo");
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException es) {
                    cs.close();
                } finally {
                    try {
                        fis.close();
                    } catch (IOException ex) {
                        Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }



        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException se) {
            System.out.println("ERROR: " + se.getMessage());
        }

        return modifico;
    }

    public Image cargarFoto(String id) {
        try {
            co.Conectar();
            Connection connection = co.getCn();

            if (connection != null) {

                PreparedStatement ps = connection.prepareStatement("select foto from FOTOPACIENTE where idpaciente = ?");
                try {
                    ps.setString(1, id);
                    ResultSet resultSet = ps.executeQuery();

                    int i = 0;
                    while (resultSet.next()) {
                        //se lee la cadena de bytes de la base de datos
                        byte[] b = resultSet.getBytes("foto");
                        // esta cadena de bytes sera convertida en una imagen
                        data = ConvertirImagen(b, "jpg");
                        i++;
                    }

                    ps.close();
                } catch (SQLException es) {
                    System.out.println("ha ocurrido un error con sql");
                } catch (FileNotFoundException e) {
                    System.out.println("archivo no encontrado");
                } catch (IOException ioe) {

                    System.out.println("error al escribir el archivo");
                }
            }


        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FotoPacienteDAOMysql.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException se) {
            System.out.println("ERROR: " + se.getMessage());
        }
        System.out.println("fotoClass/ termino de cargar");
        return data;
    }

    private Image ConvertirImagen(byte[] bytes, String formato) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName(formato);
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        return reader.read(0, param);
    }
}

